package org.example.workbench.controller;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.example.commons.constant.Constant;
import org.example.commons.domain.ErrorInfo;
import org.example.commons.utils.DateFormatUtils;
import org.example.commons.utils.HSSFUtils;
import org.example.commons.utils.UUIDUtils;
import org.example.settings.domain.User;
import org.example.settings.service.UserService;
import org.example.workbench.domain.ActivityRemark;
import org.example.workbench.domain.activity;
import org.example.workbench.service.ActivityRemarkService;
import org.example.workbench.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

@Controller
@RequestMapping("/activity")
public class activitycontroller {

    @Autowired
    private UserService service;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private ActivityRemarkService remarkService;
    @RequestMapping("/getActivityNotConnectContactsId")
    public @ResponseBody Object getActivityNotConnectContactsId(@RequestParam Map<String,Object> map){
        return activityService.getActivityNotConnectContactsId(map);
    }
    @RequestMapping("/index")
    public String index(HttpServletRequest request){
        List<User> userList = service.findAll();
        request.setAttribute("userList",userList);
        return "workbench/activity/index";
    }
    @RequestMapping("/addActivity")
    @ResponseBody
    public Object addActivity(activity activity, HttpSession session){
        ErrorInfo errorInfo = new ErrorInfo();
        try {
            User user = (User) session.getAttribute(Constant.SESSION_USER);
            activity.setCreateBy(user.getId());
            activity.setId(UUIDUtils.getUUID());
            activity.setCreateTime(DateFormatUtils.formatDateTime(new Date()));
            int i = activityService.insertActivity(activity);
            if (i<=0){
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
                errorInfo.setErrorMessage("系统繁忙，请稍后......");
            }else {
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_SUCCESS);
            }
        }catch (Exception e){
            e.printStackTrace();
            errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
            errorInfo.setErrorMessage("系统繁忙，请稍后......");
        }
        return errorInfo;
    }
    @RequestMapping("/showPages")
    @ResponseBody
    public Object showPages(String name,String owner,String startDate,String endDate,int currentPage,int pageSize){
        HashMap<String, Object> map = new HashMap<>();
        int pageNo = (currentPage-1)*pageSize;
        map.put("name",name);
        map.put("owner",owner);
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        map.put("pageNo",pageNo);
        map.put("pageSize",pageSize);
        List<activity> activities = activityService.activityList(map);
        int totalCount = activityService.getTotalCount(map);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("activityList",activities);
        hashMap.put("totalCount",totalCount);
        return hashMap;
    }
    @RequestMapping("/deleteActivityByIds")
    @ResponseBody
    public Object deleteActivityByIds(String[] id){
        ErrorInfo errorInfo = new ErrorInfo();
        try {
            int i = activityService.deleteActivityByIds(id);
            if (i>0){
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_SUCCESS);
            }else{
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
                errorInfo.setErrorMessage("系统繁忙，正在拼命加载中.....");
            }
        }catch (Exception e){
            e.printStackTrace();
            errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
            errorInfo.setErrorMessage("系统繁忙，正在拼命加载中.....");
        }
        return errorInfo;
    }
    @RequestMapping("/findOneActivityById")
    @ResponseBody
    public Object findOneActivityById(String id){
        return activityService.findOneActivityById(id);
    }
    @RequestMapping("/updateActivity")
    @ResponseBody
    public Object updateActivity(activity activity,HttpSession session){
        User user = (User) session.getAttribute(Constant.SESSION_USER);
        activity.setEditBy(user.getId());
        activity.setEditTime(DateFormatUtils.formatDateTime(new Date()));
        ErrorInfo errorInfo = new ErrorInfo();
        try {
            int i = activityService.updateActivity(activity);
            if (i>0){
                errorInfo.setErrorCode("1");
                errorInfo.setErrorMessage("修改成功！");
            }else{
                errorInfo.setErrorCode("0");
                errorInfo.setErrorMessage("系统繁忙，请稍后....");
            }
        }catch (Exception e){
            e.printStackTrace();
            errorInfo.setErrorCode("0");
            errorInfo.setErrorMessage("系统繁忙，请稍后....");
        }
        return errorInfo;
    }
    @RequestMapping("/fileDownLoad")
    public void fileDown(HttpServletResponse response) throws IOException {
        response.setContentType("application/-excel;charset=utf-8");
        /*
        设置响应头，使浏览器直接激活下载程序而不是直接在浏览器上打开；
         */
        response.setHeader("Content-Disposition","attachment;filename=students.xls");
        FileInputStream input = new FileInputStream("D:\\ideaWorkSpace\\CRM\\src\\test\\resources\\students.xls");
        ServletOutputStream output = response.getOutputStream();
        byte[] bytes = new byte[1024];
        int len=0;
        while((len=input.read(bytes))!=-1){
            output.write(bytes,0,len);
        }
        input.close();
        output.flush();
    }
    @RequestMapping("/selectActivityIntoExcel")
    public void selectActivityIntoExcel(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("市场活动表");
        HSSFRow firstRow = sheet.createRow(0);
        firstRow.createCell(0).setCellValue("id");
        firstRow.createCell(1).setCellValue("拥有者");
        firstRow.createCell(2).setCellValue("名称");
        firstRow.createCell(3).setCellValue("开始时间");
        firstRow.createCell(4).setCellValue("结束时间");
        firstRow.createCell(5).setCellValue("成本");
        firstRow.createCell(6).setCellValue("描述");
        firstRow.createCell(7).setCellValue("创建时间");
        firstRow.createCell(8).setCellValue("创建者");
        firstRow.createCell(9).setCellValue("修改时间");
        firstRow.createCell(10).setCellValue("修改者");
        List<activity> activities = activityService.selectActivityIntoExcel();
        activity activity =null;
        for (int i=0;i<activities.size();i++) {
            activity = activities.get(i);
            HSSFRow row = sheet.createRow(i+1);
            row.createCell(0).setCellValue(activity.getId());
            row.createCell(1).setCellValue(activity.getOwner());
            row.createCell(2).setCellValue(activity.getName());
            row.createCell(3).setCellValue(activity.getStartDate());
            row.createCell(4).setCellValue(activity.getEndDate());
            row.createCell(5).setCellValue(activity.getCost());
            row.createCell(6).setCellValue(activity.getDescription());
            row.createCell(7).setCellValue(activity.getCreateTime());
            row.createCell(8).setCellValue(activity.getCreateBy());
            row.createCell(9).setCellValue(activity.getEditTime());
            row.createCell(10).setCellValue(activity.getEditBy());
        }
        response.setContentType("application/-excel;charset=utf-8");
        /*
        设置响应头，使浏览器直接激活下载程序而不是直接在浏览器上打开；
         */
        response.setHeader("Content-Disposition","attachment;filename=activityList.xls");
        workbook.write(response.getOutputStream());
        workbook.close();
    }
    @RequestMapping("/selectSomeActivityIntoExcel")
    public void selectSomeActivityIntoExcel(HttpServletResponse response,String[] id) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("市场活动表");
        HSSFRow firstRow = sheet.createRow(0);
        firstRow.createCell(0).setCellValue("id");
        firstRow.createCell(1).setCellValue("拥有者");
        firstRow.createCell(2).setCellValue("名称");
        firstRow.createCell(3).setCellValue("开始时间");
        firstRow.createCell(4).setCellValue("结束时间");
        firstRow.createCell(5).setCellValue("成本");
        firstRow.createCell(6).setCellValue("描述");
        firstRow.createCell(7).setCellValue("创建时间");
        firstRow.createCell(8).setCellValue("创建者");
        firstRow.createCell(9).setCellValue("修改时间");
        firstRow.createCell(10).setCellValue("修改者");
        List<activity> activities = activityService.selectSomeActivityIntoExcel(id);
        activity activity =null;
        for (int i=0;i<activities.size();i++) {
            activity = activities.get(i);
            HSSFRow row = sheet.createRow(i+1);
            row.createCell(0).setCellValue(activity.getId());
            row.createCell(1).setCellValue(activity.getOwner());
            row.createCell(2).setCellValue(activity.getName());
            row.createCell(3).setCellValue(activity.getStartDate());
            row.createCell(4).setCellValue(activity.getEndDate());
            row.createCell(5).setCellValue(activity.getCost());
            row.createCell(6).setCellValue(activity.getDescription());
            row.createCell(7).setCellValue(activity.getCreateTime());
            row.createCell(8).setCellValue(activity.getCreateBy());
            row.createCell(9).setCellValue(activity.getEditTime());
            row.createCell(10).setCellValue(activity.getEditBy());
        }
        response.setContentType("application/-excel;charset=utf-8");
        /*
        设置响应头，使浏览器直接激活下载程序而不是直接在浏览器上打开；
         */
        response.setHeader("Content-Disposition","attachment;filename=activityList.xls");
        workbook.write(response.getOutputStream());
        workbook.close();
    }
    @RequestMapping("/fileupload")
    public void fileupload(MultipartFile myfile,HttpServletResponse response,HttpServletRequest request) throws IOException {
        String filename = myfile.getOriginalFilename();
        File file = new File("D:\\ideaWorkSpace\\CRM\\src\\test\\resources", filename);
        myfile.transferTo(file);
        response.sendRedirect(request.getContextPath()+"/index.jsp");
    }
    @RequestMapping("/insertActivityFromExcel")
    @ResponseBody
    public Object insertActivityFromExcel(MultipartFile activityFile,HttpSession session){
        ErrorInfo errorInfo = new ErrorInfo();
        try {
            ArrayList<activity> activityList = new ArrayList<>();
            InputStream input = activityFile.getInputStream();
            HSSFWorkbook workbook = new HSSFWorkbook(input);
            HSSFSheet sheet = workbook.getSheetAt(0);
            //将数据定义在外，可以提高效率，不用每次都创建相应的对象。
            HSSFRow row =null;
            HSSFCell cell=null;
            String value =null;
            for (int i = 1; i <=sheet.getLastRowNum(); i++) {
                row = sheet.getRow(i);
                activity activity = new activity();
                activity.setId(UUIDUtils.getUUID());
                User user = (User)session.getAttribute(Constant.SESSION_USER);
                activity.setOwner(user.getId());
                activity.setCreateTime(DateFormatUtils.formatDateTime(new Date()));
                activity.setCreateBy(user.getId());
                for (int j = 0; j < row.getLastCellNum(); j++) {
                    cell = row.getCell(j);
                    value = HSSFUtils.getCellValueToStr(cell);
                    if(j==0){
                        activity.setName(value);
                    } else if (j == 1) {
                        activity.setStartDate(value);
                    } else if (j == 2) {
                        activity.setEndDate(value);
                    }else if (j==3){
                        activity.setCost(value);
                    } else if (j == 4) {
                        activity.setDescription(value);
                    }
                }
                activityList.add(activity);
            }
            int rows = sheet.getLastRowNum();
            int i = activityService.insertActivityFromExcel(activityList);
            errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_SUCCESS);
            errorInfo.setErrorMessage("成功插入"+rows+"条！");
        } catch (Exception e) {
            errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
            errorInfo.setErrorMessage("系统繁忙,请稍后.....");
            throw new RuntimeException(e);
        }
        return errorInfo;
    }
    @RequestMapping("/selectRemarksAndActivities")
    public String selectRemarksAndActivities(String id,HttpServletRequest request){
        activity activity = activityService.selectActivityIntoRemark(id);
        List<ActivityRemark> activityRemarks = remarkService.selectRemarksByActivityId(id);
        request.setAttribute("activity",activity);
        request.setAttribute("activityRemarks",activityRemarks);
        return "workbench/activity/detail";
    }
}
